package com.airsystem.pos.bengkel.service.strategy;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.airsystem.pos.bengkel.entity.DetailSparepart;
import com.airsystem.pos.bengkel.interfaces.IStrategy;
import com.airsystem.pos.bengkel.service.SparepartServices;
import com.airsystem.pos.bengkel.util.HibernateUtil;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class SparepartManyStrategy implements IStrategy<DetailSparepart> {
	private static final Logger LOG = Logger.getLogger(SparepartManyStrategy.class.getSimpleName());

	private final SparepartServices sparepartServices = new SparepartServices();

	public Iterable<DetailSparepart> get(DetailSparepart data) {
		List<DetailSparepart> list = new LinkedList<DetailSparepart>();
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			Criteria cr = session.createCriteria(DetailSparepart.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

			if (data.getSub_merk() != null) {
				cr.add(Restrictions.like("sub_merk", data.getSub_merk()));
			}

			if (data.getDetail_kendaraan() != null && data.getDetail_kendaraan().getSub_merk() != null) {
				/* INNER JOIN by Default */
				cr.createAlias("detail_kendaraan", "dtken");
				cr.add(Restrictions.eq("dtken.sub_merk", data.getDetail_kendaraan().getSub_merk()));
			}

			if (data.getJenis_sparepart() != null && data.getJenis_sparepart().getId() != null) {
				/* INNER JOIN by Default */
				cr.createAlias("jenis_sparepart", "jsp");
				cr.add(Restrictions.eq("jsp.id", data.getJenis_sparepart().getId()));
			}

			if (data.getSparepart() != null && data.getSparepart().getMerk() != null) {
				/* INNER JOIN by Default */
				cr.createAlias("sparepart", "sp");
				cr.add(Restrictions.eq("sp.id", data.getSparepart().getMerk()));
			}

			List<?> results = cr.list();
			list = sparepartServices.getParser().doParse(results);

			LOG.info("Many strategy result is " + results.size());
		} finally {
			session.close();
		}

		return list;
	}
}